from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from . import models
from rest_framework import status
from .serializer import *
from django.core.paginator import Paginator

# 登录
class LoginView(APIView):
    def post(self,request):
        username=request.data.get('username','').strip()
        password = request.data.get('password', '').strip()

        userobj=models.User.objects.filter(username=username,password=password).first()
        if userobj:
            return Response('登录成功',status=status.HTTP_200_OK)
        return Response('用户名或密码错误',status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 部门
class DepartmentView(APIView):
    def post(self,request):
        name=request.data.get('name','').strip()

        deptobj=models.Department.objects.filter(name=name).first()
        if deptobj:
            return Response('数据已存在',status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        data={
            'name':name,
        }

        obj=DepartmentSerializer(data=data)

        if obj.is_valid():
            obj.save()
            return Response('添加成功', status=status.HTTP_200_OK)

        print(obj.errors)

        return Response('参数有误', status=status.HTTP_500_INTERNAL_SERVER_ERROR)


    def get(self,request):
        deptaueryset=models.Department.objects.all()
        obj=DepartmentSerializer(deptaueryset,many=True)
        return Response(obj.data)




# 员工
class UserView(APIView):
    # 读取数据
    def get(self,request):

        p=request.GET.get('p',1)

        goodquerset=models.User.objects.all()

        page_obj=Paginator(goodquerset,per_page=5)

        # 获取分页的范围
        page=[i for i in page_obj.page_range]

        # 获取当前页的数据
        page_data=page_obj.page(p)
        # 获取上一页和下一页
        previous=page_data.has_previous()
        next=page_data.has_next()

        # 序列化当前数据
        obj=UserSerializer(page_data,many=True)

        # 构造数据
        data={
            'data':obj.data,
            'page':page,
            'previous':previous,
            'next':next
        }

        # 返回
        return Response(data)





    # 添加商品
    def post(self,request):
        # 1 接收参数
        username=request.data.get('username','').strip()
        password = request.data.get('password', '').strip()
        dept = request.data.get('dept', '0')

        # 验证数据的重复性
        userobj=models.User.objects.filter(username=username).first()
        if userobj:
            return Response('数据已存在',status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        data={
            'username':username,
            'password':password,
            'dept':dept,
        }

        # 反序列化
        obj=UserSerializer(data=data)

        if obj.is_valid():
            obj.save()
            return Response('添加成功')

        print(obj.errors)
        return Response('参数有误',status=status.HTTP_500_INTERNAL_SERVER_ERROR)

